from git import Repo
import os
# @ 需要转义符号
URL="https://934033568%40qq.com:Chen9340@gitee.com/lingya_v587/huiwei-rtc.git"
PATH="E:\Python\workspace\czb"
def pullGit():
    if os.path.exists(PATH):
        print("target dir not empty,clearing...")
        del_files2(PATH)
    else:pass
    print("pullGit")
    cloneRepo = Repo.clone_from(url=URL, to_path=PATH)
    remote = cloneRepo.remote()
    remote.pull("master")
    print("代码拉取完成")
    repo = Repo(PATH)
    branches = repo.remote().refs
    for item in branches:
        print(item.remote_head)

    switchCommit("a772147fedcd05b02bb99e5e3af02d4043819eaf")

def switchCommit(commit):
    repo = Repo(PATH)
    before = repo.git.branch()
    print("切换前branch ："+ before)
    after=repo.git.checkout(commit)
    print("切换后branch ："+ after)

def del_files2(dir_path):
    # os.walk会得到dir_path下各个后代文件夹和其中的文件的三元组列表，顺序自内而外排列，
    # 如 log下有111文件夹，111下有222文件夹：[('D:\\log\\111\\222', [], ['22.py']), ('D:\\log\\111', ['222'], ['11.py']), ('D:\\log', ['111'], ['00.py'])]
    for root, dirs, files in os.walk(dir_path, topdown=False):
        print(root) # 各级文件夹绝对路径
        print(dirs) # root下一级文件夹名称列表，如 ['文件夹1','文件夹2']
        print(files)  # root下文件名列表，如 ['文件1','文件2']
        # 第一步：删除文件
        for name in files:
            os.remove(os.path.join(root, name))  # 删除文件
        # 第二步：删除空文件夹
        for name in dirs:
            os.rmdir(os.path.join(root, name)) # 删除一个空目录

pullGit()